"""
配置服务 - 重构后的简化版本
支持本地配置文件管理，移除复杂的远程拉取逻辑
"""

import json
import logging
import os
from pathlib import Path
from typing import Dict, Any, Optional

from ..core.types import OperationResult


logger = logging.getLogger(__name__)


class ConfigService:
    """简化的配置服务"""
    
    def __init__(self, config_dir: str = None):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.config_dir = Path(config_dir or '/home/mobox/mobox_dashboard/config')
        self.config_cache_dir = Path('/tmp/mobox_configs')
        self.config_cache_dir.mkdir(exist_ok=True)
        
        # 确保配置目录存在
        self.config_dir.mkdir(exist_ok=True)
    
    def get_school_config(self, school_name: str) -> OperationResult:
        """
        获取学校配置（简化版本，从本地读取）
        
        Args:
            school_name: 学校名称
            
        Returns:
            OperationResult: 包含学校配置的结果
        """
        try:
            # 标准化学校名称作为文件名
            config_filename = f"{school_name}.json"
            config_path = self.config_dir / config_filename
            
            if config_path.exists():
                with open(config_path, 'r', encoding='utf-8') as f:
                    config_data = json.load(f)
                
                return OperationResult(
                    success=True,
                    message=f"成功读取学校配置: {school_name}",
                    details={
                        "school_name": school_name,
                        "config_data": config_data,
                        "config_path": str(config_path)
                    }
                )
            else:
                # 返回默认配置
                default_config = self._get_default_config(school_name)
                return OperationResult(
                    success=True,
                    message=f"使用默认配置: {school_name}",
                    details={
                        "school_name": school_name,
                        "config_data": default_config,
                        "is_default": True
                    }
                )
                
        except Exception as e:
            self.logger.error(f"获取学校配置失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取学校配置失败: {str(e)}",
                error=str(e)
            )
    
    def save_school_config(self, school_name: str, config_data: Dict[str, Any]) -> OperationResult:
        """
        保存学校配置
        
        Args:
            school_name: 学校名称
            config_data: 配置数据
            
        Returns:
            OperationResult: 操作结果
        """
        try:
            config_filename = f"{school_name}.json"
            config_path = self.config_dir / config_filename
            
            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, ensure_ascii=False, indent=2)
            
            return OperationResult(
                success=True,
                message=f"学校配置保存成功: {school_name}",
                details={
                    "school_name": school_name,
                    "config_path": str(config_path)
                }
            )
            
        except Exception as e:
            self.logger.error(f"保存学校配置失败: {e}")
            return OperationResult(
                success=False,
                message=f"保存学校配置失败: {str(e)}",
                error=str(e)
            )
    
    def get_current_school_info(self) -> Optional[Dict[str, Any]]:
        """获取当前学校信息"""
        try:
            current_school_file = self.config_dir / 'current_school.json'
            
            if current_school_file.exists():
                with open(current_school_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            
            return None
            
        except Exception as e:
            self.logger.error(f"读取当前学校信息失败: {e}")
            return None
    
    def set_current_school_info(self, school_name: str, school_id: str = None, 
                               base_image: str = None) -> OperationResult:
        """设置当前学校信息"""
        try:
            school_info = {
                "school_name": school_name,
                "school_id": school_id or "",
                "base_image": base_image or "mobox-python-hardware:latest",
                "updated_at": "2024-01-01T00:00:00"
            }
            
            current_school_file = self.config_dir / 'current_school.json'
            
            with open(current_school_file, 'w', encoding='utf-8') as f:
                json.dump(school_info, f, ensure_ascii=False, indent=2)
            
            return OperationResult(
                success=True,
                message=f"当前学校信息设置成功: {school_name}",
                details=school_info
            )
            
        except Exception as e:
            self.logger.error(f"设置当前学校信息失败: {e}")
            return OperationResult(
                success=False,
                message=f"设置当前学校信息失败: {str(e)}",
                error=str(e)
            )
    
    def list_available_configs(self) -> OperationResult:
        """列出所有可用的配置文件"""
        try:
            config_files = []
            
            for config_file in self.config_dir.glob('*.json'):
                # 跳过系统配置文件
                if config_file.name in ['current_school.json', 'pattern_matching.json', 'update_mode.json']:
                    continue
                
                try:
                    with open(config_file, 'r', encoding='utf-8') as f:
                        config_data = json.load(f)
                    
                    config_files.append({
                        "filename": config_file.name,
                        "school_name": config_file.stem,
                        "path": str(config_file),
                        "has_docker_config": "docker" in config_data
                    })
                except Exception as e:
                    self.logger.warning(f"读取配置文件失败 {config_file}: {e}")
                    continue
            
            return OperationResult(
                success=True,
                message=f"找到 {len(config_files)} 个配置文件",
                details={
                    "config_files": config_files,
                    "total_count": len(config_files)
                }
            )
            
        except Exception as e:
            self.logger.error(f"列出配置文件失败: {e}")
            return OperationResult(
                success=False,
                message=f"列出配置文件失败: {str(e)}",
                error=str(e)
            )
    
    def validate_config(self, config_data: Dict[str, Any]) -> OperationResult:
        """验证配置文件格式"""
        try:
            required_fields = ['school_name']
            missing_fields = []
            
            for field in required_fields:
                if field not in config_data:
                    missing_fields.append(field)
            
            if missing_fields:
                return OperationResult(
                    success=False,
                    message=f"配置缺少必需字段: {', '.join(missing_fields)}",
                    error=f"Missing required fields: {missing_fields}"
                )
            
            # 验证Docker配置（如果存在）
            if 'docker' in config_data:
                docker_config = config_data['docker']
                if not isinstance(docker_config, dict):
                    return OperationResult(
                        success=False,
                        message="Docker配置格式错误",
                        error="Docker config must be a dictionary"
                    )
                
                if 'services' in docker_config:
                    services = docker_config['services']
                    if not isinstance(services, list):
                        return OperationResult(
                            success=False,
                            message="Docker服务配置格式错误",
                            error="Services config must be a list"
                        )
            
            return OperationResult(
                success=True,
                message="配置验证通过",
                details={"validated_fields": list(config_data.keys())}
            )
            
        except Exception as e:
            return OperationResult(
                success=False,
                message=f"配置验证失败: {str(e)}",
                error=str(e)
            )
    
    def _get_default_config(self, school_name: str) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            "school_name": school_name,
            "docker": {
                "registry": {
                    "url": "crpi-axr6nxua9k92sqiz.cn-hangzhou.personal.cr.aliyuncs.com/mobox-docker",
                    "namespace": "mobox-docker"
                },
                "services": [
                    {
                        "name": "mobox-python-service",
                        "image": "mobox-python-hardware",
                        "tag": "latest",
                        "port": 8080,
                        "enabled": True
                    }
                ]
            },
            "created_at": "2024-01-01T00:00:00",
            "is_default": True
        }